/**
 * Chrowety
 * oauth.js
*/

var
OAuth = {};

OAuth.tokenAtual = null;
OAuth.token = [];
OAuth.consumer = {};

/**
 * Inicia a porra toda
 * @param consumer_key {String}
 * @param consumer_secret {String}
 */
OAuth.init = function( consumer_key, consumer_secret )
{
    if( !consumer_key || !consumer_secret )
    	return console.error('OAuth.init ERROR: ConsumerKey or ConsumerSecret not DEFINED!', consumer_key, consumer_secret);

    this.consumer.key    = consumer_key;
    this.consumer.secret = consumer_secret;
};

/**
 * Sign
 * @param url {String}
 * @param dados {Object}
 * @param method {String}
 * @param opts {Object}
 */
OAuth.Sign = function(url, dados, method, opts)
{
    var 
    sig = {
    	'consumer_key': this.consumer.key,
        'shared_secret': this.consumer.secret
    },
    Tk = this.token[this.tokenAtual],
    currentTk = opts['token'] || cfg.getToken();
    
    if( !opts['noToken'] )
    {
	    if( Tk && Tk.oauth_token )
	    {
	        sig.oauth_token = Tk.oauth_token;
	        sig.oauth_secret = Tk.oauth_token_secret;
	    }
	    else
	    {
	        sig.oauth_token = currentTk.oauth_token;
	        sig.oauth_secret = currentTk.oauth_token_secret;    	
	    }    	
    }
    
    return OAuthSimple().sign({
        'path': url,
        'action': method ? method : 'GET',
        'parameters': dados ? dados : {},
        'signatures':  sig
    });
};

/**
 * Request Token
 * @param callback {Function}
 */
OAuth.requestToken = function( callback )
{
	OAuth.newTemporaryToken();
	
	twitter.requestToken(function(sucesso, result){
		if(sucesso)
		{
	        var args = result.split("&");
	        for(i in args)
	        {
	        	if(typeof args[i] != 'string') 
	        		continue;
	            args[i] = args[i].split("=");
	            OAuth.token[OAuth.tokenAtual][args[i][0]] = args[i][1];
	        }
	        console.log('RequestToken Sucessfully received..');
	        if(callback) callback(true, OAuth.token[OAuth.tokenAtual]);
		}
		else
		{
			//this.token['erro'] = true;
            console.log('RequestToken Failed..');
            if(callback) callback(false);
		}	
	});
};

/**
 * Access Token
 * @param pin {Int}
 * @param callback {Function}
 */
OAuth.accessToken = function(pin, callback)
{
	twitter.accessToken(pin, function(sucesso, result){
		if(sucesso)
		{
            var args = result.split("&");
            for(i in args)
            {
            	if(typeof args[i] != 'string') 
            		continue;
            	args[i] = args[i].split("=");
            	OAuth.token[OAuth.tokenAtual][args[i][0]] = args[i][1];
            }
            console.log('AccessToken Sucessfully received..');
	        if(callback) callback(true, OAuth.token[OAuth.tokenAtual]);
		}
		else
		{
			console.log('AccessToken Failed..');
            if(callback) callback(false, result);
		}
	});
};

/**
 * xAuth Access Token
 * @param username {String}
 * @param password {String}
 * @param callback {Function}
 */
OAuth.xAccessToken = function(username, password, callback)
{
	OAuth.newTemporaryToken();
	
    twitter.xAccessToken(username, password, function(sucesso, result){
		if(sucesso)
		{
            var args = result.split("&");
            for(i in args)
            {
            	if(typeof args[i] != 'string') 
            		continue;
            	args[i] = args[i].split("=");
            	OAuth.token[OAuth.tokenAtual][args[i][0]] = args[i][1];
            }
            console.log('AccessToken Sucessfully received..');            
	        if(callback) callback(true, OAuth.token[OAuth.tokenAtual]);
		}
		else
		{
			console.log('AccessToken Failed..');
            if(callback) callback(false, result);
		}    	
    });
};

/**
 * Cria um alocador de token temporario
 * @param token {Object}
 */
OAuth.newTemporaryToken = function( token )
{
	this.clearToken();
	this.tokenAtual = 'tempToken_' + utils.time.randomNumber();
	this.token[this.tokenAtual] = token || {};	
};

/**
 * Limpa o Token temporario
 */
OAuth.clearToken = function()
{
    delete OAuth.token[OAuth.tokenAtual];
    OAuth.tokenAtual = null;
};

OAuth.init('eWGZ2e24PmM301P1i0f6bQ','4zwn3jgT4To5Hl6i4fPGkB3mBqkP3Sif5rTVKLPuqg');